package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.Meter;
import com.ruoyi.system.domain.MeterRecord;
import com.ruoyi.system.domain.MeterRecordAdd;
import com.ruoyi.system.domain.vo.MeterRecordVO;
import com.ruoyi.system.domain.vo.MeterVO;
import com.ruoyi.system.mapper.MeterMapper;
import com.ruoyi.system.mapper.MeterRecordAddMapper;
import com.ruoyi.system.mapper.MeterRecordMapper;
import com.ruoyi.system.service.IMeterRecordService;
import com.ruoyi.system.service.ISysConfigService;

/**
 * 电记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-10-29
 */
@Service
public class MeterRecordServiceImpl implements IMeterRecordService 
{
    @Autowired
    private MeterRecordMapper meterRecordMapper;
    @Autowired
    private MeterRecordAddMapper meterRecordAddMapper;
    @Autowired
    private MeterMapper meterMapper;
    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 查询电记录
     * 
     * @param id 电记录主键
     * @return 电记录
     */
    @Override
    public MeterRecord selectMeterRecordById(Long id)
    {
        return meterRecordMapper.selectMeterRecordById(id);
    }

    /**
     * 查询电记录列表
     * 
     * @param meterRecord 电记录
     * @return 电记录
     */
    @Override
    public List<MeterRecord> selectMeterRecordList(MeterRecordVO meterRecord)
    {
        return meterRecordMapper.selectMeterRecordList(meterRecord);
    }
    
    @Override
    public List<MeterRecordVO> selectMeterRecordListNew(MeterRecordVO meterRecord) {
    	return meterRecordMapper.selectMeterRecordListNew(meterRecord);
    }
    
    @Transactional
    @Override
    public AjaxResult returnZero(Long meterId) {
    	MeterRecordVO meterRecordN = new MeterRecordVO();
    	meterRecordN.setMeterId(meterId);
		MeterRecord list = meterRecordMapper.selectMeterRecordSum(meterRecordN );
		if (list == null ) {
			return AjaxResult.error("没有数据不用归0");
		}
		
		Meter selectMeterById = meterMapper.selectMeterById(meterId);
		
		BigDecimal rechargeValue = list.getRechargeValue().negate();
		BigDecimal everyValue = list.getEveryValue().negate();
		BigDecimal shareValue = list.getShareValue().negate();
		
		
		MeterRecord record = new MeterRecord();
		record.setRechargeValue(rechargeValue);
		record.setShareValue(shareValue);
		record.setEveryValue(everyValue);
		record.setMeterId(meterId);
		record.setType(3);
		record.setTotalEle(selectMeterById.getMeterValue());
		record.setCreateTime(new Date());
		record.setIsDeleted(0);
		meterRecordMapper.insertMeterRecord(record );
		
		Meter meter  = new Meter();
		meter.setId(meterId);
		meter.setMeterValue(BigDecimal.ZERO);
		meter.setMeterWarn(BigDecimal.ZERO);
		meterMapper.updateMeter(meter  );
		
    	return AjaxResult.success();
    }
    
    public static void main(String[] args) {
    		System.out.println(new BigDecimal(0).negate());
	}

    /**
     * 新增电记录
     * 
     * @param meterRecord 电记录
     * @return 结果
     */
    @Override
    public int insertMeterRecord(MeterRecord meterRecord)
    {
        meterRecord.setCreateTime(DateUtils.getNowDate());
        return meterRecordMapper.insertMeterRecord(meterRecord);
    }

	@Override
	public MeterRecord selectMeterRecordSum(MeterRecordVO meterRecord) {
		return meterRecordMapper.selectMeterRecordSumNew(meterRecord);
	}
    /**
     * 修改电记录
     * 
     * @param meterRecord 电记录
     * @return 结果
     */
    @Override
    public int updateMeterRecord(MeterRecord meterRecord)
    {
        meterRecord.setUpdateTime(DateUtils.getNowDate());
        return meterRecordMapper.updateMeterRecord(meterRecord);
    }

    /**
     * 批量删除电记录
     * 
     * @param ids 需要删除的电记录主键
     * @return 结果
     */
    @Override
    public int deleteMeterRecordByIds(Long[] ids)
    {
        return meterRecordMapper.deleteMeterRecordByIds(ids);
    }

    /**
     * 删除电记录信息
     * 
     * @param id 电记录主键
     * @return 结果
     */
    @Override
    public int deleteMeterRecordById(Long id)
    {
        return meterRecordMapper.deleteMeterRecordById(id);
    }
    
    
    @Override
    public void meterRecordTask() {
    	
    	Meter meter = new Meter();
    	meter.setIsDeleted(0);
		List<MeterVO> selectMeterList = meterMapper.selectMeterList(meter );
		if (CollectionUtils.isEmpty(selectMeterList)) {
			return;
		}
		List<Long> meterIds = new ArrayList<>();
		//总表
		List<Long> meterOverIds = new ArrayList<>();
		for (Meter e : selectMeterList) {
			meterIds.add(e.getId());
			if (e.getOverall().equals(2)) {
				meterOverIds.add(e.getId());
			}
		}
		
		
    	//凌晨 0.00.1
    	Date date = new Date();
    	//昨天时间，当天数据
    	Date dateYesterday = DateUtils.dateAdd(DateUtils.INTERVAL_DAY, date, -1);
//    	Date startDateYesterday = DateUtils.getStartDate(dateYesterday);
    	Date finallyDateYesterday = DateUtils.getFinallyDate(dateYesterday);
//    	
    	//前天时间  ，昨天数据
    	Date dateYesterdayYesterday = DateUtils.dateAdd(DateUtils.INTERVAL_DAY, date, -2);
    	Date startDateYesterdayYesterday = DateUtils.getStartDate(dateYesterdayYesterday);
    	Date finallyDateYesterdayYesterday = DateUtils.getFinallyDate(dateYesterdayYesterday);
    	
    	List<MeterRecordAdd> selectMeterRecordAddTimeListYesterdayYesterday = meterRecordAddMapper
    			.selectMeterRecordAddTimeList(startDateYesterdayYesterday, finallyDateYesterdayYesterday);
    	if (CollectionUtils.isEmpty(selectMeterRecordAddTimeListYesterdayYesterday)) {
			for (Long e : meterIds) {
				MeterRecordAdd meterRecordAdd = new MeterRecordAdd();
				meterRecordAdd.setMeterId(e);
				meterRecordAdd.setToday(BigDecimal.ZERO);
				selectMeterRecordAddTimeListYesterdayYesterday.add(meterRecordAdd);
			}
		}
    	
    	//也就是今天数据，
    	List<MeterRecordAdd> today = new ArrayList<>();
    	
    	Map<Long, List<MeterRecordAdd>> collect = selectMeterRecordAddTimeListYesterdayYesterday.stream().collect(Collectors.groupingBy(MeterRecordAdd::getMeterId));
    	
    	
    	for (Meter e : selectMeterList) {
    		MeterRecordAdd mAdd = new MeterRecordAdd();
    		mAdd.setMeterId(e.getId());
    		mAdd.setCreateTime(finallyDateYesterday);
    		mAdd.setUpdateTime(date);
    		
    		BigDecimal meterValueNow = e.getMeterValue();
    		
    		MeterRecordAdd meterRecordAdd = collect.get(e.getId()).get(0);
    		BigDecimal yesterDayValue = meterRecordAdd.getToday().add(meterRecordAdd.getBeforeMeterValue());
    		
//    		mAdd.setToday(meterValueNow);
    		mAdd.setBeforeMeterValue(yesterDayValue);
    		mAdd.setIsDeleted(0);
    		mAdd.setToday(meterValueNow.subtract(yesterDayValue));
    		mAdd.setAddEleValue(meterValueNow.subtract(yesterDayValue));
    		today.add(mAdd);
		}
    
    	dealDate(today,meterOverIds);
    }
    
    
    
    private void dealDate(List<MeterRecordAdd> today,List<Long> meterOverIds ) {
        //总变化数值
        BigDecimal totalOverChange = BigDecimal.ZERO;
        BigDecimal totalNotOverChange = BigDecimal.ZERO;
        for (MeterRecordAdd meterRecordAdd : today) {
			if (meterOverIds.contains(meterRecordAdd.getMeterId())) {
				totalOverChange = totalOverChange.add(meterRecordAdd.getAddEleValue());
			}else {
				totalNotOverChange = totalNotOverChange.add(meterRecordAdd.getAddEleValue());
			}
		}
        
        String selectConfigByKey = sysConfigService.selectConfigByKey("sys.dianbiao.price");
        BigDecimal price = new BigDecimal(selectConfigByKey);
        
        
        for (MeterRecordAdd meterRecordAdd : today) {
			if (!meterOverIds.contains(meterRecordAdd.getMeterId())) {
				BigDecimal addEleValue = meterRecordAdd.getAddEleValue();
				BigDecimal divide = addEleValue.divide(totalNotOverChange,3,BigDecimal.ROUND_HALF_DOWN).multiply(totalOverChange);
				meterRecordAdd.setAddEleValue(addEleValue.add(divide));
				meterRecordAdd.setShareValue(divide.multiply(price));
				meterRecordAdd.setEveryValue(meterRecordAdd.getToday().multiply(price));
			}else {
				BigDecimal addEleValue = meterRecordAdd.getAddEleValue();
				meterRecordAdd.setAddEleValue(addEleValue);
				meterRecordAdd.setEveryValue(meterRecordAdd.getToday().multiply(price));
			}
		}
        
      
        for (MeterRecordAdd meterRecordAdd : today) {
        	
        	Meter meter  = new Meter();
        	meter.setId(meterRecordAdd.getMeterId());
        	meter.setMeterWarn(meterRecordAdd.getAddEleValue());
			//处理度数
        	meterMapper.updateMeterWarn(meter  );
        	meterRecordAdd.setAddValue(meterRecordAdd.getAddEleValue().multiply(price));
        	meterRecordAddMapper.insertMeterRecordAdd(meterRecordAdd);
        	
        	Meter selectMeterById = meterMapper.selectMeterById(meterRecordAdd.getMeterId());
        	MeterRecord meterRecord = new MeterRecord();
        	meterRecord.setMeterId(meterRecordAdd.getMeterId());
        	meterRecord.setType(2);
        	BigDecimal everyValue = meterRecordAdd.getEveryValue();
        	if (everyValue == null ) {
				System.out.println(111);
			}
			meterRecord.setEveryValue(everyValue);
			meterRecord.setToday(everyValue.divide(price,3,BigDecimal.ROUND_HALF_DOWN));
			
        	BigDecimal shareValue = meterRecordAdd.getShareValue();
        	if (shareValue != null ) {
        		meterRecord.setShareValue(shareValue);
    			meterRecord.setTodayShare(shareValue.divide(price,3,BigDecimal.ROUND_HALF_DOWN));
    			
    			
			}
		
			meterRecord.setTotalEle(selectMeterById.getMeterValue());
        	meterRecord.setRechargeValue(meterRecordAdd.getAddValue());
        	meterRecord.setCreateTime(new Date());
        	
	
        	
        	
        	MeterRecordVO meterRecordNew = new MeterRecordVO();
			//判断今天数据 是否存在
        	meterRecordNew.setMeterId(meterRecordAdd.getMeterId());
        	meterRecordNew.setCreateTime(new Date());
        	meterRecordNew.setType(2);
//        	MeterRecord selectMeterRecordToday = meterRecordMapper.selectMeterRecordToday(meterRecordNew );
//        	if (selectMeterRecordToday == null  ) {
        		//增加记录
            	meterRecordMapper.insertMeterRecord(meterRecord );
//			}else {
//				meterRecord.setId(selectMeterRecordToday.getId());
//				meterRecordMapper.updateMeterRecord(meterRecord );
//			}
        	
        }
       
	}

    
    @Override
	public void dealDate4() {
    	List<MeterRecordAdd> selectMeterRecordAddTimeListNew = meterRecordAddMapper.selectMeterRecordAddTimeListNew("2021-11-21");
    	
    	List<MeterRecordAdd> selectMeterRecordAddTimeListNew2 = meterRecordAddMapper.selectMeterRecordAddTimeListNew("2021-11-20");
    	
//    	Map<Long, List<MeterRecordAdd>> collectNew = selectMeterRecordAddTimeListNew.stream().collect(Collectors.groupingBy(MeterRecordAdd::getMeterId));
    	Map<Long, List<MeterRecordAdd>> collectold = selectMeterRecordAddTimeListNew2.stream().collect(Collectors.groupingBy(MeterRecordAdd::getMeterId));
    	for (MeterRecordAdd meterRecordAdd : selectMeterRecordAddTimeListNew) {
    		
    		MeterRecordAdd meterRecordAddOld = collectold.get(meterRecordAdd.getMeterId()).get(0);
    		BigDecimal todayOld = meterRecordAddOld.getToday();
    		BigDecimal beforeMeterValue = meterRecordAddOld.getBeforeMeterValue();
    		
    		meterRecordAdd.setBeforeMeterValue(todayOld.add(beforeMeterValue));
    		
    		BigDecimal subtract = meterRecordAdd.getToday().add(todayOld).subtract(meterRecordAdd.getBeforeMeterValue());
    		meterRecordAdd.setToday(subtract);
    		meterRecordAdd.setAddEleValue(subtract);
    		meterRecordAdd.setEveryValue(subtract);
    		meterRecordAdd.setAddValue(subtract);
    		meterRecordAddMapper.updateMeterRecordAdd(meterRecordAdd);
    		
		}
    	
    	
    }
    
    
    //处理脚本
    public void dealData() {
    	
    	//删除数据 
    	meterRecordAddMapper.deleteMeterRecordAddByIdOther();
		List<String> list = new ArrayList<>();
		String yearMonth = "2021-11-";
		//11号电费 
//		list.add("2021-11-12 00:00:01");
//		list.add("12");
//		list.add("13");
//		list.add("14");
//		list.add("15");
//		list.add("16");
//		list.add("17");
//		list.add("18");
//		list.add("19");
//		list.add("20");
		list.add("21");
		
		//修改所有的未0 
		Meter meter = new Meter();
    	meter.setIsDeleted(0);
		List<MeterVO> selectMeterList = meterMapper.selectMeterList(meter );
		for (MeterVO meterVO : selectMeterList) {
			meterVO.setMeterWarn(BigDecimal.ZERO);
			meterMapper.updateMeter(meterVO);
		}
		
		for (String string : list) {
			//2021-11-12  算11号数据
			List<MeterRecordAdd> selectMeterRecordAddTimeListNew = meterRecordAddMapper.selectMeterRecordAddTimeListNew(yearMonth+string);
			dealData2(selectMeterRecordAddTimeListNew,new Integer(string),yearMonth);
		}
		
		for (MeterVO meterVO : selectMeterList) {
			
			MeterRecordVO e = new MeterRecordVO();
			Long id = meterVO.getId();
			e.setMeterId(id);
			MeterRecord selectMeterRecordSumCharge = meterRecordMapper.selectMeterRecordSumCharge(e);
			BigDecimal rechargeValue = selectMeterRecordSumCharge.getRechargeValue();
			Meter selectMeterById = meterMapper.selectMeterById(id);
			
			MeterRecordVO meterRecord1 = new MeterRecordVO();
			meterRecord1.setMeterId(id);
			MeterRecord selectMeterRecordSumNew = meterRecordMapper.selectMeterRecordSumNew(meterRecord1 );
			BigDecimal add = rechargeValue.subtract(selectMeterRecordSumNew.getRechargeValue());
			selectMeterById.setMeterWarn(add);
			
			meterMapper.updateMeter(selectMeterById);
			
			
		}

	}
    
    public void dealData2(	List<MeterRecordAdd> list,Integer day,String yearMonth) {
        BigDecimal totalOverChange = BigDecimal.ZERO;
        BigDecimal totalNotOverChange = BigDecimal.ZERO;
    	for (MeterRecordAdd meterRecordAdd : list) {
    		Long meterId = meterRecordAdd.getMeterId();
    		if (meterId.longValue() == 13l || meterId.longValue() == 15l) {
				totalOverChange = totalOverChange.add(meterRecordAdd.getToday());
			}else {
				totalNotOverChange = totalNotOverChange.add(meterRecordAdd.getToday());
			}
		}
        String selectConfigByKey = sysConfigService.selectConfigByKey("sys.dianbiao.price");
        BigDecimal price = new BigDecimal(selectConfigByKey);
        
    	for (MeterRecordAdd meterRecordAdd : list) {
    		Long meterId = meterRecordAdd.getMeterId();
    		BigDecimal beforeMeterValue = meterRecordAdd.getBeforeMeterValue();
    		BigDecimal today = meterRecordAdd.getToday();
    		
    		MeterRecord meterRecord = new MeterRecord();
    		if (!(meterId.longValue() == 13l || meterId.longValue() == 15l)) {
				BigDecimal divide = today.divide(totalNotOverChange,3,BigDecimal.ROUND_HALF_DOWN).multiply(totalOverChange);
				meterRecord.setTotalEle(today.add(beforeMeterValue));
				meterRecord.setTodayShare(divide);
				meterRecord.setToday(today);
				
				meterRecord.setShareValue(divide.multiply(price));
				meterRecord.setEveryValue(today.multiply(price));
				meterRecord.setRechargeValue((divide.add(today)).multiply(price));
			}else {
				meterRecord.setToday(today);
				meterRecord.setTotalEle(today.add(beforeMeterValue));
				
				meterRecord.setEveryValue(today.multiply(price));
				meterRecord.setRechargeValue(today.multiply(price));
			}
    		
    		
    		
    		
        	meterRecord.setMeterId(meterRecordAdd.getMeterId());
        	meterRecord.setType(2);
//        	String create = yearMonth+day+"00:00:01";
        	Date updateTime = meterRecordAdd.getUpdateTime();
        	meterRecord.setCreateTime(updateTime);
    		
        	MeterRecordVO meterRecordNew = new MeterRecordVO();
			//判断今天数据 是否存在
        	meterRecordNew.setMeterId(meterRecordAdd.getMeterId());
        	meterRecordNew.setCreateTime(updateTime);
        	meterRecordNew.setType(2);
        	MeterRecord selectMeterRecordToday = meterRecordMapper.selectMeterRecordToday(meterRecordNew );
			meterRecord.setId(selectMeterRecordToday.getId());
			meterRecordMapper.updateMeterRecord(meterRecord );
        	
    		
    		
    	}
    	
    	
    	
    }


}
